package com.duoec.magichour.service.impl;

import com.duoec.magichour.core.utils.ArticleUtils;
import com.duoec.magichour.dto.request.ArticleSave;
import com.duoec.magichour.dto.response.ArticleDetailDto;
import com.duoec.magichour.dto.response.ArticleListItemDto;
import com.duoec.magichour.dto.response.ProductSimpleInfoDto;
import com.duoec.magichour.dto.response.UserSimpleInfoDto;
import com.duoec.magichour.mapper.ArticleMapper;
import com.duoec.magichour.pojo.Article;
import com.duoec.magichour.service.*;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 文章服务
 * Created by ycoe on 17/6/25.
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private UserFollowService userFollowService;

    @Autowired
    private ArticleCollectionService articleCollectionService;

    @Autowired
    private ArticleProductService articleProductService;

    @Autowired
    private ArticlePhotoService articlePhotoService;

    @Autowired
    private ArticleCateService articleCateService;

    @Override
    public List<ArticleListItemDto> getRecommends(long userId, int pageNo, int pageSize) {
        List<Article> articleList = articleMapper.recommends((pageNo - 1) * pageSize, pageSize);
        if (articleList == null) {
            return Lists.newArrayList();
        }
        return setArticleList(userId, articleList);
    }

    @Override
    public List<ArticleListItemDto> getCollection(long userId, int pageNo, int pageSize) {
        List<Article> articleList = articleMapper.collection(userId, (pageNo - 1) * pageSize, pageSize);
        if (articleList == null) {
            return Lists.newArrayList();
        }
        return setArticleList(userId, articleList);
    }

    @Override
    public List<ArticleListItemDto> searchArticles(long userId, String keyword, int pageNo, int pageSize) {
        List<Article> articleList = articleMapper.search(keyword, (pageNo - 1) * pageSize, pageSize);
        if (articleList == null) {
            return Lists.newArrayList();
        }
        return setArticleList(userId, articleList);
    }

    @Override
    public ArticleDetailDto getDetail(long userId, long articleId) {
        Article article = articleMapper.selectByPrimaryKey(articleId);
        if (article == null) {
            return null;
        }

        ArticleDetailDto detail = new ArticleDetailDto();
        BeanUtils.copyProperties(article, detail);

        //收藏状态
        boolean collected = articleCollectionService.getUserCollectionArticle(articleId, userId);
        detail.setCollected(collected);

        //关注状态
        boolean follow = userFollowService.follow(userId, article.getUserId());
        detail.setFollow(follow);

        //关联商品
        if (article.getProductCount() != null && article.getProductCount() > 0) {
            List<ProductSimpleInfoDto> products = articleProductService.getByArticleId(articleId);
            detail.setProducts(products);
        }

        return detail;
    }

    @Override
    public boolean exists(Long articleId) {
        Integer count = articleMapper.countById(articleId);
        return count != null;
    }

    @Override
    public void incArticleCommentCount(Long articleId) {
        articleMapper.incArticleCommentCount(articleId);
    }

//    @Transactional
    @Override
    public ArticleListItemDto save(UserSimpleInfoDto userInfo, ArticleSave request) {
        Date now = new Date();
        Article article = new Article();
        article.setTitle(request.getTitle());
        article.setContent(request.getContent());

        if(request.getCateId() != null && request.getCateId() > 0) {
            article.setCateId(request.getCateId());
        }

        article.setUpdateTime(now);
        article.setUserId(userInfo.getId());
        if (request.getRelease() != null && request.getRelease() == 1) {
            // 发布上线
            article.setArticleStatus((byte) 1);
        } else {
            article.setArticleStatus((byte) 0);
        }

        //保存图片
        List<String> photoList = request.getPhotos();
        Set<String> photoSet = Sets.newHashSet();
        photoList.forEach(url -> {
            if (Strings.isNullOrEmpty(url)) {
                return;
            }
            if (article.getCoverImg() == null) {
                //取第一张图片作为封面图
                article.setCoverImg(url);
            }
            photoSet.add(url);
        });

        article.setImgCount(photoSet.size());

        //自动生成概要
        String summary = ArticleUtils.getSubText(request.getContent(), 150);
        article.setSummary(summary);

        if (request.getId() != null && request.getId() > 0) {
            //修改
            article.setId(request.getId());
            articleMapper.updateByPrimaryKeySelective(article);
        } else {
            //新增
            article.setProductCount(0);
            article.setShareCount(0);
            article.setTopicCount(0);
            article.setViewCount(0);
            article.setCollectCount(0);
            article.setCommendCount(0);
            article.setCreateTime(now);
            articleMapper.insertSelective(article);
        }

        //保存图片
        articlePhotoService.setArticlePhotos(article.getId(), photoSet);

        //处理 @

        //处理话题

        //处理商品

        //处理关联文章

        //用户发布文章数+1
        userService.incArticleCount(userInfo.getId());

        List<ArticleListItemDto> list = setArticleList(userInfo.getId(), Lists.newArrayList(article));
        return list.get(0);
    }

    @Override
    public void incArticleCollection(long articleId) {
        articleMapper.incArticleCollection(articleId);
    }

    @Override
    public Long getArticleAuthor(long articleId) {
        return articleMapper.getArticleAuthor(articleId);
    }

    @Override
    public void decArticleCommentCount(long articleId) {
        articleMapper.decArticleCommentCount(articleId);
    }

    @Override
    public void changeArticleCate(int articleCateId, int newArticleCateId) {
        articleMapper.changeArticleCate(articleCateId, newArticleCateId);
    }

    @Override
    public List<ArticleListItemDto> getUserArticles(Long currentUserId, long authorUserId, int pageNo, int pageSize) {
        List<Article> articleList = articleMapper.userArticleList(authorUserId, (pageNo - 1) * pageSize, pageSize);
        if (articleList == null) {
            return Lists.newArrayList();
        }
        return setArticleList(currentUserId, articleList);
    }

    private List<ArticleListItemDto> setArticleList(long userId, List<Article> articleList) {
        List<ArticleListItemDto> articleListItemDtoList = Lists.newArrayList();
        List<Long> userIdList = Lists.newArrayList();
        articleList
                .stream()
                .filter(article -> !userIdList.contains(article.getUserId()))
                .forEach(article -> userIdList.add(article.getUserId()));

        //获取收藏状态
        Set<Long> articleIdSet = articleCollectionService.getUserCollectionArticleSet(userIdList, userId);

        Map<Long, UserSimpleInfoDto> userSimpleInfoMap = userService.getUserSimpleInfoMap(userIdList);
        articleList.forEach(article -> {
            ArticleListItemDto item = new ArticleListItemDto();
            BeanUtils.copyProperties(article, item);

            //用户基本信息
            long authorId = article.getUserId();
            UserSimpleInfoDto userInfo = userSimpleInfoMap.get(authorId);
            if (userInfo != null) {
                item.setUserInfo(userInfo);
            }

            //文章分类
            Integer cateId = article.getCateId();
            if(cateId != null && cateId > 0) {
                item.setCateName(articleCateService.getName(cateId));
            }

            //收藏状态
            item.setCollected(articleIdSet.contains(article.getId()));

            articleListItemDtoList.add(item);
        });

        return articleListItemDtoList;
    }
}
